package com.tim.library.third;

import android.text.TextUtils;

import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMOfflinePushConfig;
import com.tencent.qcloud.tim.tuiofflinepush.utils.BrandUtil;
import com.tencent.qcloud.tim.tuiofflinepush.utils.TUIOfflinePushLog;

/**
 * 用来保存厂商注册离线推送token的管理类示例，
 * 当登陆im后，通过 setOfflinePushToken 上报证书 ID 及设备 token 给im后台。
 * 开发者可以根据自己的需求灵活实现
 */
public class ThirdPushTokenManager {

    private static final String TAG = ThirdPushTokenManager.class.getSimpleName();
    private String mThirdPushToken;

    public static ThirdPushTokenManager getInstance() {
        return ThirdPushTokenHolder.instance;
    }

    private static class ThirdPushTokenHolder {
        private static final ThirdPushTokenManager instance = new ThirdPushTokenManager();
    }

    public String getThirdPushToken() {
        return mThirdPushToken;
    }

    public void setThirdPushToken(String mThirdPushToken) {
        this.mThirdPushToken = mThirdPushToken;
    }

    public void setPushTokenToTIM() {
        String token = ThirdPushTokenManager.getInstance().getThirdPushToken();

        if (TextUtils.isEmpty(token)) {
            TUIOfflinePushLog.e(TAG, "setPushTokenToTIM third token is empty");
            return;
        }

        V2TIMOfflinePushConfig v2TIMOfflinePushConfig;
        if (BrandUtil.isBrandXiaoMi()) {
            v2TIMOfflinePushConfig = new V2TIMOfflinePushConfig(Constants.XM_PUSH_BUZID, token);
        } else if (BrandUtil.isBrandHuawei()) {
            v2TIMOfflinePushConfig = new V2TIMOfflinePushConfig(Constants.HW_PUSH_BUZID, token);
        } else if (BrandUtil.isBrandMeizu()) {
            v2TIMOfflinePushConfig = new V2TIMOfflinePushConfig(Constants.MZ_PUSH_BUZID, token);
        } else if (BrandUtil.isBrandOppo()) {
            v2TIMOfflinePushConfig = new V2TIMOfflinePushConfig(Constants.OPPO_PUSH_BUZID, token);
        } else if (BrandUtil.isBrandVivo()) {
            v2TIMOfflinePushConfig = new V2TIMOfflinePushConfig(Constants.VIVO_PUSH_BUZID, token);
        } else {
            return;
        }

        V2TIMManager
                .getOfflinePushManager()
                .setOfflinePushConfig(
                        v2TIMOfflinePushConfig,
                        new V2TIMCallback() {
                            @Override
                            public void onError(int code, String desc) {
                                TUIOfflinePushLog.e(TAG, "setOfflinePushToken error code = " + code);
                            }

                            @Override
                            public void onSuccess() {
                                TUIOfflinePushLog.d(TAG, "setOfflinePushToken success");
                            }
                        }
                );
    }

}
